# 先导入基本模块进行测试
import sys
import os

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
print(f"当前工作目录: {os.getcwd()}")
print(f"Python路径: {sys.path}")

# 基本模块导入
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import FileResponse
from datetime import timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Dict, Any, Optional
from datetime import datetime
import logging

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/reports", tags=["reports"])

# 逐步测试导入
print("开始测试导入 database 模块...")
try:
    from database.connection import get_session as get_db
    print("✅ database.connection 导入成功")
except ImportError as e:
    print(f"❌ database.connection 导入失败: {e}")

print("开始测试导入 services 模块...")
try:
    from services.report_service import ReportService
    print("✅ services.report_service 导入成功")
except ImportError as e:
    print(f"❌ services.report_service 导入失败: {e}")

print("开始测试导入 api.users 模块...")
try:
    from api.users import get_current_user
    print("✅ api.users 导入成功")
except ImportError as e:
    print(f"❌ api.users 导入失败: {e}")
    # 如果导入失败，创建一个空的get_current_user函数作为临时解决方案
    async def get_current_user():
        from database.models import User
        return User(id=1, username="admin", email="admin@example.com", role="admin")

print("开始测试导入 database.models 模块...")
try:
    from database.models import User
    print("✅ database.models 导入成功")
except ImportError as e:
    print(f"❌ database.models 导入失败: {e}")


@router.get("/dashboard", response_model=Dict[str, Any])
async def get_dashboard_stats(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取仪表板统计数据"""
    try:
        report_service = ReportService(db)
        stats = await report_service.get_dashboard_stats()
        return {
            "success": True,
            "data": stats,
            "message": "仪表板数据获取成功"
        }
    except Exception as e:
        logger.error(f"获取仪表板数据失败: {e}")
        raise HTTPException(status_code=500, detail="获取仪表板数据失败")


@router.get("/orders/status", response_model=Dict[str, Any])
async def get_order_status_stats(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取订单状态统计"""
    try:
        report_service = ReportService(db)
        stats = await report_service.get_order_stats_by_status()
        return {
            "success": True,
            "data": stats,
            "message": "订单状态统计获取成功"
        }
    except Exception as e:
        logger.error(f"获取订单状态统计失败: {e}")
        raise HTTPException(status_code=500, detail="获取订单状态统计失败")


@router.get("/revenue", response_model=Dict[str, Any])
async def get_revenue_stats(
    days: int = Query(default=30, ge=1, le=365, description="统计天数"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取收入统计"""
    try:
        report_service = ReportService(db)
        stats = await report_service.get_revenue_stats(days)
        return {
            "success": True,
            "data": stats,
            "message": f"最近{days}天收入统计获取成功"
        }
    except Exception as e:
        logger.error(f"获取收入统计失败: {e}")
        raise HTTPException(status_code=500, detail="获取收入统计失败")


@router.get("/products", response_model=Dict[str, Any])
async def get_product_stats(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取商品统计"""
    try:
        report_service = ReportService(db)
        stats = await report_service.get_product_stats()
        return {
            "success": True,
            "data": stats,
            "message": "商品统计获取成功"
        }
    except Exception as e:
        logger.error(f"获取商品统计失败: {e}")
        raise HTTPException(status_code=500, detail="获取商品统计失败")


@router.get("/users", response_model=Dict[str, Any])
async def get_user_stats(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取用户统计"""
    try:
        report_service = ReportService(db)
        stats = await report_service.get_user_stats()
        return {
            "success": True,
            "data": stats,
            "message": "用户统计获取成功"
        }
    except Exception as e:
        logger.error(f"获取用户统计失败: {e}")
        raise HTTPException(status_code=500, detail="获取用户统计失败")


@router.get("/production", response_model=Dict[str, Any])
async def get_production_stats(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取生产统计"""
    try:
        report_service = ReportService(db)
        stats = await report_service.get_production_stats()
        return {
            "success": True,
            "data": stats,
            "message": "生产统计获取成功"
        }
    except Exception as e:
        logger.error(f"获取生产统计失败: {e}")
        raise HTTPException(status_code=500, detail="获取生产统计失败")


@router.get("/monthly", response_model=Dict[str, Any])
async def get_monthly_report(
    year: int = Query(default=datetime.now().year, ge=2020, le=2030),
    month: int = Query(default=datetime.now().month, ge=1, le=12),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取月度报告"""
    try:
        report_service = ReportService(db)
        report = await report_service.get_monthly_report(year, month)
        return {
            "success": True,
            "data": report,
            "message": f"{year}年{month}月度报告获取成功"
        }
    except Exception as e:
        logger.error(f"获取月度报告失败: {e}")
        raise HTTPException(status_code=500, detail="获取月度报告失败")


@router.get("/export/{report_type}", response_model=Dict[str, Any])
async def export_report(
    report_type: str,
    format: str = Query(default="json", regex="^(json|csv|xlsx)$"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """导出报表"""
    try:
        report_service = ReportService(db)
        
        # 根据报表类型和格式导出数据
        if format == "xlsx":
            # 计算默认日期范围（最近30天）
            end_date = datetime.now()
            start_date = end_date - timedelta(days=30)
            # Excel导出 - 使用支持的报表类型
            supported_types = ["all", "orders", "users", "products", "production", "revenue"]
            if report_type not in supported_types:
                logger.warning(f"不支持的报表类型 '{report_type}'，使用 'all' 类型")
                report_type = "all"
            
            # 确保导出目录存在
            export_dir = "uploads/reports"
            os.makedirs(export_dir, exist_ok=True)
            
            # Excel导出
            logger.info(f"调用export_report方法，参数: report_type={report_type}, format={format}, start_date={start_date}, end_date={end_date}")
            excel_file = await report_service.export_report(report_type, format, start_date, end_date)
            return {
                "success": True,
                "data": {
                    "report_type": report_type,
                    "format": format,
                    "export_time": datetime.now().isoformat(),
                    "file_path": excel_file,
                    "download_url": f"/api/reports/download/{excel_file.replace(os.sep, '/').split('/')[-1]}"
                },
                "message": f"{report_type}报表导出成功"
            }
        else:
            # JSON格式导出（原有逻辑）
            if report_type == "dashboard":
                data = await report_service.get_dashboard_stats()
            elif report_type == "orders":
                data = await report_service.get_order_stats_by_status()
            elif report_type == "revenue":
                data = await report_service.get_revenue_stats()
            elif report_type == "products":
                data = await report_service.get_product_stats()
            elif report_type == "users":
                data = await report_service.get_user_stats()
            elif report_type == "production":
                data = await report_service.get_production_stats()
            else:
                raise HTTPException(status_code=400, detail="不支持的报表类型")
            
            return {
                "success": True,
                "data": {
                    "report_type": report_type,
                    "format": format,
                    "export_time": datetime.now().isoformat(),
                    "data": data
                },
                "message": f"{report_type}报表导出成功"
            }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"导出报表失败: {e}")
        logger.error(f"错误详情: {str(e)}")
        import traceback
        logger.error(f"错误堆栈: {traceback.format_exc()}")
        raise HTTPException(status_code=500, detail=f"导出报表失败: {str(e)}")


@router.get("/download/{filename}")
async def download_report(
    filename: str,
    current_user: User = Depends(get_current_user)
):
    """下载导出的报表文件"""
    try:
        # 构建文件路径
        file_path = os.path.join("uploads/reports", filename)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="文件不存在")
        
        # 返回文件
        return FileResponse(
            file_path,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            filename=filename
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"下载报表文件失败: {e}")
        raise HTTPException(status_code=500, detail="下载报表文件失败")